#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
using namespace std;

int main()
{
    int pipefd[2];
    pid_t pid;
    char buf[100];

    // 创建管道
    if (pipe(pipefd) == -1)
    {
        perror("pipe");
        exit(1);
    }

    // 创建子进程
    pid = fork();
    if (pid == -1)
    {
        perror("fork");
        exit(1);
    }

    // 子进程
    if (pid == 0)
    {
        // 关闭写端
        close(pipefd[1]);

        // 读取数据ssize_t read(int __fd, void *__buf, size_t __nbytes)
        ssize_t s = read(pipefd[0], buf, sizeof(buf) - 1);
        if (s > 0)
        {
            buf[s] = 0; // 字符串自定义约定
            printf("Child received: %s\n", buf);
        }
        else if (s == 0)
        {
            cout << "child: father(writer) exit, me(reader) quit!" << endl
                 << endl;
            exit(1);
        }

        // 关闭读端
        close(pipefd[0]);
        exit(0);
    }
    // 父进程
    else
    {
        // 关闭读端
        close(pipefd[0]);

        // 写入数据
        const char *msg = "i am father";
        write(pipefd[1], msg, strlen(msg));

        // 关闭写端
        close(pipefd[1]);

        // 等待子进程结束
        waitpid(pid, nullptr, 0);
        exit(0);
    }

    return 0;
}